package com.qyhl.webtv.module_news.news.union.special.detail;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.SpecialDetailBean;
import com.qyhl.webtv.commonlib.entity.news.UnionBean;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemUnion;
import com.qyhl.webtv.commonlib.item.ItemUnionLarge;
import com.qyhl.webtv.commonlib.item.ItemUnionTag;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

/**
 * Created by qyhl on 2017/12/4.
 * 专题详情
 */

@Route(path = ARouterPathConstant.DETAIL_SPECIAL)
public class SpecialDetailActivity extends BaseActivity implements SpecialDetailContract.SpecialDetailView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.recycle_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.go_top)
    ImageView goTop;
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.share_btn)
    ImageView shareBtn;
    @BindView(R2.id.divider)
    ImageView divider;

    private SpecialDetailPresenter mPresenter;

    @Autowired(name = "title")
    String mTitle;

    @Autowired(name = "cover")
    String mCover;

    @Autowired(name = "id")
    String sectionId;
    private TagFlowLayout flowLayout;

    private List<UnionBean> sectionList;

    private List<GlobalNewsBean> mDataList;

    private List<SpecialDetailBean> mList;

    private MultiItemTypeAdapter<GlobalNewsBean> mAdapter;

    private LinearLayoutManager linearLayoutManager;

    private HeaderAndFooterWrapper<GlobalNewsBean> headerAndFooterWrapper;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_union_detail_special;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SpecialDetailPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getSecitons(sectionId);
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        sectionList = new ArrayList<>();
        mList = new ArrayList<>();
        mDataList = new ArrayList<>();

        //Glide配置
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.cover_large_default)
                .error(R.drawable.cover_large_default)
                .priority(Priority.HIGH);
        //初始化头部
        View headView = LayoutInflater.from(this).inflate(R.layout.news_header_special_detail, null);
        ImageView cover = (ImageView) headView.findViewById(R.id.cover);
        flowLayout = (TagFlowLayout) headView.findViewById(R.id.flowlayout);

        title.setText(StringUtils.isEmpty(mTitle) ? "专题详情" : mTitle);

        if (StringUtils.isEmpty(mCover)) {
            cover.setVisibility(View.GONE);
        } else {
            cover.setVisibility(View.VISIBLE);
        }

        Glide.with(this)
                .load(mCover)
                .apply(options)
                .into(cover);

        //刷新
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setEnableLoadMore(false);
        refresh.setDisableContentWhenRefresh(true);

        //设置布局管理器
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(this, R.drawable.news_item_listview_divider)));
        recyclerView.addItemDecoration(divider);

        //初始化适配器
        mAdapter = new MultiItemTypeAdapter<GlobalNewsBean>(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(this));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(this));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(this));
        mAdapter.addItemViewDelegate(new ItemCatchNews(this));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(this));
        mAdapter.addItemViewDelegate(new ItemCommonRight(this));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(this));
        mAdapter.addItemViewDelegate(new ItemGoodLife(this));
        mAdapter.addItemViewDelegate(new ItemNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemPicture(this));
        mAdapter.addItemViewDelegate(new ItemTitleNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(this));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(this));
        mAdapter.addItemViewDelegate(new ItemVideoRight(this));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(this));
        mAdapter.addItemViewDelegate(new ItemUnion(this));
        mAdapter.addItemViewDelegate(new ItemUnionLarge(this));
        mAdapter.addItemViewDelegate(new ItemUnionTag());
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(this));
        headerAndFooterWrapper = new HeaderAndFooterWrapper(mAdapter);
        headerAndFooterWrapper.addHeaderView(headView);
        recyclerView.setAdapter(headerAndFooterWrapper);

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.getSecitons(sectionId);
            }
        });

        //重载
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getSecitons(sectionId);
            }
        });

        //流布局点击
        flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                try {
                    int index;
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getTitle().equals(sectionList.get(position).getName())) {
                            index = i;
                            linearLayoutManager.scrollToPositionWithOffset(index + 1, 0);
                        }
                    }
                    return true;
                } catch (Exception e) {
                    return true;
                }

            }
        });

        //返回顶部
        goTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.scrollToPosition(0);
                goTop.setVisibility(View.GONE);
            }
        });

        //返回监听
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //分享
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(SpecialDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        MShareBoard shareBoard = new MShareBoard(SpecialDetailActivity.this, sectionId, mTitle, mCover, "", CommonUtils.getInstance().getBannerId(), 12);
                        shareBoard.showPopupWindow();
//                        ShareUtils.getInstance().goShare(sectionId, 12, "", mTitle, mCover, SpecialDetailActivity.this);
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(SpecialDetailActivity.this);
                    }
                });
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position != 0) {
                    GlobalNewsBean bean = mDataList.get(position - 1);
                    ItemSkipUtils.getInstance().itemSkip(bean, SpecialDetailActivity.this);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 设置栏目
     *
     * @param beanList
     */
    @Override
    public void setSection(List<UnionBean> beanList) {
        sectionList = beanList;
        String mSections = "";

        for (int i = 0; i < beanList.size(); i++) {
            if (i == (beanList.size() - 1)) {
                mSections = mSections + beanList.get(i).getId();
            } else {
                mSections = mSections + beanList.get(i).getId() + ",";
            }
        }

        flowLayout.setAdapter(new TagAdapter<UnionBean>(sectionList) {
            @Override
            public View getView(FlowLayout parent, int position, UnionBean o) {
                TextView tv = (TextView) LayoutInflater.from(getApplicationContext()).inflate(R.layout.news_item_special_detail_flowlayout,
                        flowLayout, false);
                tv.setText(o.getName());
                return tv;
            }
        });

        mPresenter.getDatas(mSections);

    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishRefresh();
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 设置新闻内容
     *
     * @param beanList
     */
    @Override
    public void setDatas(List<SpecialDetailBean> beanList) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        mList = beanList;

        List<GlobalNewsBean> indexList = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            indexList.add(new GlobalNewsBean(sectionList.get(i).getName(), "", "", "", sectionList.size(), "", "100", i + 1, "", mList.get(i).getSection(), true, null));
            if (mList.get(i).getTopicNews() != null && mList.get(i).getTopicNews().size() > 0) {
                for (int j = 0; j < mList.get(i).getTopicNews().size(); j++) {
                    NewsBean bean = mList.get(i).getTopicNews().get(j);
                    boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
                    String type = "", pOne = "", pTwo = "", pThree = "";
                    int style = 0;
                    switch (bean.getType()) {
                        case "1"://普通新闻
                            type = "1";
                            switch (bean.getPluralPicsFlag()) {
                                case 0:
                                    style = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
                                    break;
                                case 1://三图
                                    hasPicture = false;
                                    if (bean.getImagess().size() == 1) {
                                        hasPicture = true;
                                        pOne = bean.getImagess().get(0).getImageUrlString();
                                    } else if (bean.getImagess().size() == 2) {
                                        pOne = bean.getImagess().get(0).getImageUrlString();
                                        pTwo = bean.getImagess().get(1).getImageUrlString();
                                        hasPicture = true;
                                    } else if (bean.getImagess().size() >= 3) {
                                        pOne = bean.getImagess().get(0).getImageUrlString();
                                        pTwo = bean.getImagess().get(1).getImageUrlString();
                                        pThree = bean.getImagess().get(2).getImageUrlString();
                                        hasPicture = true;
                                    } else {
                                        hasPicture = false;
                                    }
                                    style = 4;
                                    break;
                                case 2:
                                    style = 3;
                                    break;
                                default:
                                    style = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
                                    break;
                            }
                            break;
                        case "2"://图片新闻
                            type = "2";
                            if (bean.getImagess().size() == 1) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                hasPicture = true;
                            } else if (bean.getImagess().size() == 2) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                pTwo = bean.getImagess().get(1).getImageUrlString();
                                hasPicture = true;
                            } else if (bean.getImagess().size() >= 3) {
                                pOne = bean.getImagess().get(0).getImageUrlString();
                                pTwo = bean.getImagess().get(1).getImageUrlString();
                                pThree = bean.getImagess().get(2).getImageUrlString();
                                hasPicture = true;
                            } else {
                                hasPicture = false;
                            }
                            break;
                        case "3"://直播
                            type = "9";
                            break;
                        case "4"://标题新闻
                            type = "8";
                            break;
                        case "5"://视频新闻
                            type = "3";
                            style = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
                            break;
                        case "8"://互动直播
                            bean.setID(bean.getRoomId());//将roomId设置成通用Id
                            type = "5";
                            break;
                        case "101"://抓取新闻
                            type = "10";
                            break;
                        default:
                            break;
                    }
                    indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
                }
            }
        }

        mDataList.clear();
        mDataList.addAll(indexList);
        headerAndFooterWrapper.notifyDataSetChanged();

    }
}
